home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / python2.6 / logging / config.py < prev    next >
Encoding:
Python Source  |  2010-12-26  |  13.1 KB  |  384 lines

  1. # Copyright 2001-2007 by Vinay Sajip. All Rights Reserved.
  2. #
  3. # Permission to use, copy, modify, and distribute this software and its
  4. # documentation for any purpose and without fee is hereby granted,
  5. # provided that the above copyright notice appear in all copies and that
  6. # both that copyright notice and this permission notice appear in
  7. # supporting documentation, and that the name of Vinay Sajip
  8. # not be used in advertising or publicity pertaining to distribution
  9. # of the software without specific, written prior permission.
  10. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
  11. # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL
  12. # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
  13. # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  14. # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
  15. # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16.  
  17. """
  18. Configuration functions for the logging package for Python. The core package
  19. is based on PEP 282 and comments thereto in comp.lang.python, and influenced
  20. by Apache's log4j system.
  21.  
  22. Should work under Python versions >= 1.5.2, except that source line
  23. information is not available unless 'sys._getframe()' is.
  24.  
  25. Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved.
  26.  
  27. To use, simply 'import logging' and log away!
  28. """
  29.  
  30. import sys, logging, logging.handlers, string, socket, struct, os, traceback, types
  31.  
  32. try:
  33.     import thread
  34.     import threading
  35. except ImportError:
  36.     thread = None
  37.  
  38. from SocketServer import ThreadingTCPServer, StreamRequestHandler
  39.  
  40.  
  41. DEFAULT_LOGGING_CONFIG_PORT = 9030
  42.  
  43. if sys.platform == "win32":
  44.     RESET_ERROR = 10054   #WSAECONNRESET
  45. else:
  46.     RESET_ERROR = 104     #ECONNRESET
  47.  
  48. #
  49. #   The following code implements a socket listener for on-the-fly
  50. #   reconfiguration of logging.
  51. #
  52. #   _listener holds the server object doing the listening
  53. _listener = None
  54.  
  55. def fileConfig(fname, defaults=None, disable_existing_loggers=1):
  56.     """
  57.     Read the logging configuration from a ConfigParser-format file.
  58.  
  59.     This can be called several times from an application, allowing an end user
  60.     the ability to select from various pre-canned configurations (if the
  61.     developer provides a mechanism to present the choices and load the chosen
  62.     configuration).
  63.     In versions of ConfigParser which have the readfp method [typically
  64.     shipped in 2.x versions of Python], you can pass in a file-like object
  65.     rather than a filename, in which case the file-like object will be read
  66.     using readfp.
  67.     """
  68.     import ConfigParser
  69.  
  70.     cp = ConfigParser.ConfigParser(defaults)
  71.     if hasattr(cp, 'readfp') and hasattr(fname, 'readline'):
  72.         cp.readfp(fname)
  73.     else:
  74.         cp.read(fname)
  75.  
  76.     formatters = _create_formatters(cp)
  77.  
  78.     # critical section
  79.     logging._acquireLock()
  80.     try:
  81.         logging._handlers.clear()
  82.         del logging._handlerList[:]
  83.         # Handlers add themselves to logging._handlers
  84.         handlers = _install_handlers(cp, formatters)
  85.         _install_loggers(cp, handlers, disable_existing_loggers)
  86.     finally:
  87.         logging._releaseLock()
  88.  
  89.  
  90. def _resolve(name):
  91.     """Resolve a dotted name to a global object."""
  92.     name = string.split(name, '.')
  93.     used = name.pop(0)
  94.     found = __import__(used)
  95.     for n in name:
  96.         used = used + '.' + n
  97.         try:
  98.             found = getattr(found, n)
  99.         except AttributeError:
  100.             __import__(used)
  101.             found = getattr(found, n)
  102.     return found
  103.  
  104. def _strip_spaces(alist):
  105.     return map(lambda x: string.strip(x), alist)
  106.  
  107. def _encoded(s):
  108.     return s if isinstance(s, str) else s.encode('utf-8')
  109.  
  110. def _create_formatters(cp):
  111.     """Create and return formatters"""
  112.     flist = cp.get("formatters", "keys")
  113.     if not len(flist):
  114.         return {}
  115.     flist = string.split(flist, ",")
  116.     flist = _strip_spaces(flist)
  117.     formatters = {}
  118.     for form in flist:
  119.         sectname = "formatter_%s" % form
  120.         opts = cp.options(sectname)
  121.         if "format" in opts:
  122.             fs = cp.get(sectname, "format", 1)
  123.         else:
  124.             fs = None
  125.         if "datefmt" in opts:
  126.             dfs = cp.get(sectname, "datefmt", 1)
  127.         else:
  128.             dfs = None
  129.         c = logging.Formatter
  130.         if "class" in opts:
  131.             class_name = cp.get(sectname, "class")
  132.             if class_name:
  133.                 c = _resolve(class_name)
  134.         f = c(fs, dfs)
  135.         formatters[form] = f
  136.     return formatters
  137.  
  138.  
  139. def _install_handlers(cp, formatters):
  140.     """Install and return handlers"""
  141.     hlist = cp.get("handlers", "keys")
  142.     if not len(hlist):
  143.         return {}
  144.     hlist = string.split(hlist, ",")
  145.     hlist = _strip_spaces(hlist)
  146.     handlers = {}
  147.     fixups = [] #for inter-handler references
  148.     for hand in hlist:
  149.         sectname = "handler_%s" % hand
  150.         klass = cp.get(sectname, "class")
  151.         opts = cp.options(sectname)
  152.         if "formatter" in opts:
  153.             fmt = cp.get(sectname, "formatter")
  154.         else:
  155.             fmt = ""
  156.         try:
  157.             klass = eval(klass, vars(logging))
  158.         except (AttributeError, NameError):
  159.             klass = _resolve(klass)
  160.         args = cp.get(sectname, "args")
  161.         args = eval(args, vars(logging))
  162.         h = klass(*args)
  163.         if "level" in opts:
  164.             level = cp.get(sectname, "level")
  165.             h.setLevel(logging._levelNames[level])
  166.         if len(fmt):
  167.             h.setFormatter(formatters[fmt])
  168.         if issubclass(klass, logging.handlers.MemoryHandler):
  169.             if "target" in opts:
  170.                 target = cp.get(sectname,"target")
  171.             else:
  172.                 target = ""
  173.             if len(target): #the target handler may not be loaded yet, so keep for later...
  174.                 fixups.append((h, target))
  175.         handlers[hand] = h
  176.     #now all handlers are loaded, fixup inter-handler references...
  177.     for h, t in fixups:
  178.         h.setTarget(handlers[t])
  179.     return handlers
  180.  
  181.  
  182. def _install_loggers(cp, handlers, disable_existing_loggers):
  183.     """Create and install loggers"""
  184.  
  185.     # configure the root first
  186.     llist = cp.get("loggers", "keys")
  187.     llist = string.split(llist, ",")
  188.     llist = map(lambda x: string.strip(x), llist)
  189.     llist.remove("root")
  190.     sectname = "logger_root"
  191.     root = logging.root
  192.     log = root
  193.     opts = cp.options(sectname)
  194.     if "level" in opts:
  195.         level = cp.get(sectname, "level")
  196.         log.setLevel(logging._levelNames[level])
  197.     for h in root.handlers[:]:
  198.         root.removeHandler(h)
  199.     hlist = cp.get(sectname, "handlers")
  200.     if len(hlist):
  201.         hlist = string.split(hlist, ",")
  202.         hlist = _strip_spaces(hlist)
  203.         for hand in hlist:
  204.             log.addHandler(handlers[hand])
  205.  
  206.     #and now the others...
  207.     #we don't want to lose the existing loggers,
  208.     #since other threads may have pointers to them.
  209.     #existing is set to contain all existing loggers,
  210.     #and as we go through the new configuration we
  211.     #remove any which are configured. At the end,
  212.     #what's left in existing is the set of loggers
  213.     #which were in the previous configuration but
  214.     #which are not in the new configuration.
  215.     existing = root.manager.loggerDict.keys()
  216.     #The list needs to be sorted so that we can
  217.     #avoid disabling child loggers of explicitly
  218.     #named loggers. With a sorted list it is easier
  219.     #to find the child loggers.
  220.     existing.sort(key=_encoded)
  221.     #We'll keep the list of existing loggers
  222.     #which are children of named loggers here...
  223.     child_loggers = []
  224.     #now set up the new ones...
  225.     for log in llist:
  226.         sectname = "logger_%s" % log
  227.         qn = cp.get(sectname, "qualname")
  228.         opts = cp.options(sectname)
  229.         if "propagate" in opts:
  230.             propagate = cp.getint(sectname, "propagate")
  231.         else:
  232.             propagate = 1
  233.         logger = logging.getLogger(qn)
  234.         if qn in existing:
  235.             i = existing.index(qn)
  236.             prefixed = qn + "."
  237.             pflen = len(prefixed)
  238.             num_existing = len(existing)
  239.             i = i + 1 # look at the entry after qn
  240.             while (i < num_existing) and (existing[i][:pflen] == prefixed):
  241.                 child_loggers.append(existing[i])
  242.                 i = i + 1
  243.             existing.remove(qn)
  244.         if "level" in opts:
  245.             level = cp.get(sectname, "level")
  246.             logger.setLevel(logging._levelNames[level])
  247.         for h in logger.handlers[:]:
  248.             logger.removeHandler(h)
  249.         logger.propagate = propagate
  250.         logger.disabled = 0
  251.         hlist = cp.get(sectname, "handlers")
  252.         if len(hlist):
  253.             hlist = string.split(hlist, ",")
  254.             hlist = _strip_spaces(hlist)
  255.             for hand in hlist:
  256.                 logger.addHandler(handlers[hand])
  257.  
  258.     #Disable any old loggers. There's no point deleting
  259.     #them as other threads may continue to hold references
  260.     #and by disabling them, you stop them doing any logging.
  261.     #However, don't disable children of named loggers, as that's
  262.     #probably not what was intended by the user.
  263.     for log in existing:
  264.         logger = root.manager.loggerDict[log]
  265.         if log in child_loggers:
  266.             logger.level = logging.NOTSET
  267.             logger.handlers = []
  268.             logger.propagate = 1
  269.         elif disable_existing_loggers:
  270.             logger.disabled = 1
  271.  
  272.  
  273. def listen(port=DEFAULT_LOGGING_CONFIG_PORT):
  274.     """
  275.     Start up a socket server on the specified port, and listen for new
  276.     configurations.
  277.  
  278.     These will be sent as a file suitable for processing by fileConfig().
  279.     Returns a Thread object on which you can call start() to start the server,
  280.     and which you can join() when appropriate. To stop the server, call
  281.     stopListening().
  282.     """
  283.     if not thread:
  284.         raise NotImplementedError, "listen() needs threading to work"
  285.  
  286.     class ConfigStreamHandler(StreamRequestHandler):
  287.         """
  288.         Handler for a logging configuration request.
  289.  
  290.         It expects a completely new logging configuration and uses fileConfig
  291.         to install it.
  292.         """
  293.         def handle(self):
  294.             """
  295.             Handle a request.
  296.  
  297.             Each request is expected to be a 4-byte length, packed using
  298.             struct.pack(">L", n), followed by the config file.
  299.             Uses fileConfig() to do the grunt work.
  300.             """
  301.             import tempfile
  302.             try:
  303.                 conn = self.connection
  304.                 chunk = conn.recv(4)
  305.                 if len(chunk) == 4:
  306.                     slen = struct.unpack(">L", chunk)[0]
  307.                     chunk = self.connection.recv(slen)
  308.                     while len(chunk) < slen:
  309.                         chunk = chunk + conn.recv(slen - len(chunk))
  310.                     #Apply new configuration. We'd like to be able to
  311.                     #create a StringIO and pass that in, but unfortunately
  312.                     #1.5.2 ConfigParser does not support reading file
  313.                     #objects, only actual files. So we create a temporary
  314.                     #file and remove it later.
  315.                     file = tempfile.mktemp(".ini")
  316.                     f = open(file, "w")
  317.                     f.write(chunk)
  318.                     f.close()
  319.                     try:
  320.                         fileConfig(file)
  321.                     except (KeyboardInterrupt, SystemExit):
  322.                         raise
  323.                     except:
  324.                         traceback.print_exc()
  325.                     os.remove(file)
  326.             except socket.error, e:
  327.                 if type(e.args) != types.TupleType:
  328.                     raise
  329.                 else:
  330.                     errcode = e.args[0]
  331.                     if errcode != RESET_ERROR:
  332.                         raise
  333.  
  334.     class ConfigSocketReceiver(ThreadingTCPServer):
  335.         """
  336.         A simple TCP socket-based logging config receiver.
  337.         """
  338.  
  339.         allow_reuse_address = 1
  340.  
  341.         def __init__(self, host='localhost', port=DEFAULT_LOGGING_CONFIG_PORT,
  342.                      handler=None):
  343.             ThreadingTCPServer.__init__(self, (host, port), handler)
  344.             logging._acquireLock()
  345.             self.abort = 0
  346.             logging._releaseLock()
  347.             self.timeout = 1
  348.  
  349.         def serve_until_stopped(self):
  350.             import select
  351.             abort = 0
  352.             while not abort:
  353.                 rd, wr, ex = select.select([self.socket.fileno()],
  354.                                            [], [],
  355.                                            self.timeout)
  356.                 if rd:
  357.                     self.handle_request()
  358.                 logging._acquireLock()
  359.                 abort = self.abort
  360.                 logging._releaseLock()
  361.  
  362.     def serve(rcvr, hdlr, port):
  363.         server = rcvr(port=port, handler=hdlr)
  364.         global _listener
  365.         logging._acquireLock()
  366.         _listener = server
  367.         logging._releaseLock()
  368.         server.serve_until_stopped()
  369.  
  370.     return threading.Thread(target=serve,
  371.                             args=(ConfigSocketReceiver,
  372.                                   ConfigStreamHandler, port))
  373.  
  374. def stopListening():
  375.     """
  376.     Stop the listening server which was created with a call to listen().
  377.     """
  378.     global _listener
  379.     if _listener:
  380.         logging._acquireLock()
  381.         _listener.abort = 1
  382.         _listener = None
  383.         logging._releaseLock()
  384.